package com.xuzz.study.io.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class GroupChatClient {
    final String HOST="127.0.0.1";
    final Integer PORT = 6667;

    SocketChannel socketChannel;
    Selector selector;

    String userName;

    public GroupChatClient()
    {
        try {
            socketChannel = SocketChannel.open();
            selector=Selector.open();
            socketChannel.connect(new InetSocketAddress(HOST,PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);
            userName = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(userName+" 准备好了");
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

    //像服务器发送消息
    private void sendInfo(String info)
    {
        info = userName+" 说："+info;
        try {
            ByteBuffer buffer = ByteBuffer.wrap(info.getBytes());
            socketChannel.write(buffer);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    //读取服务器返回的消息
    private void readInfo()
    {
        try {
                int readChannels = selector.select();
                if(readChannels>0)
                {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
                    while(keyIterator.hasNext())
                    {
                        SelectionKey key = keyIterator.next();
                        if(key.isConnectable())
                        {
                            System.out.println("连接到了服务器");
                        }
                        else if(key.isReadable())
                        {
                            SocketChannel sc = (SocketChannel)key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            sc.read(buffer);
                            System.out.println(new String(buffer.array()));
                        }
                    }
                }
                else
                {
                    //System.out.println("没有可以用的通道");
                }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        GroupChatClient groupChatClient=new GroupChatClient();
        new Thread(()->{
            while(true)
            {
                groupChatClient.readInfo();
                try
                {
                    Thread.currentThread().sleep(3000);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        }).start();

        Scanner input = new Scanner(System.in);
        while(input.hasNextLine())
        {
            String msg = input.nextLine();
            if("q".equals(msg.toLowerCase()))
            {
                break;
            }
            groupChatClient.sendInfo(msg);
        }
    }
}
